﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CslaDesigner
{
    static class XmlManager
    {
        /// <summary>
        /// 读取
        /// </summary>
        /// <param name="t"></param>
        /// <param name="xmlName"></param>
        /// <returns></returns>
        public static object Load(Type t, string xmlName)
        {
            if (!System.IO.File.Exists(xmlName)) return null;
            else
            {
                object obj = null;

                using (System.IO.StreamReader sr = new System.IO.StreamReader(xmlName, System.Text.Encoding.Unicode))
                {
                    System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(t);
                    obj = xml.Deserialize(sr);
                    sr.Close();
                }
                return obj;
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="xmlName"></param>
        /// <param name="cfg"></param>
        public static void Save(string xmlName, object cfg)
        {
            if (cfg == null) throw new ArgumentNullException();

            Type t = cfg.GetType();
            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(xmlName));

            using (System.IO.StreamWriter sr = new System.IO.StreamWriter(xmlName, false, System.Text.Encoding.Unicode))
            {
                System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(t);
                xml.Serialize(sr, cfg);
                sr.Close();
            }
        }

    }
}
